package com.wlps.aspect;

import com.wlps.result.ResultCode;
import com.wlps.result.ResultUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

@Order(1)
@Aspect
@Component
public class BindingResultAspect {
    /**
     *   拦截public方法 所有类型的返回值 ，controller 所有类的所有方法任意参数
     */
    @Pointcut("execution(public * com.wlps.controller.*.*(..))")
    public void bindResult(){}
    @Around("bindResult()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for(Object arg:args){
            if(arg instanceof BindingResult){
                BindingResult result=(BindingResult)arg;
                if(result.hasErrors()){
                    FieldError fieldError = result.getFieldError();
                    if(fieldError!=null){
                        return ResultUtils.error(fieldError.getDefaultMessage());
                    }
                    else{
                        return ResultUtils.error(ResultCode.VALIDATE_FAILED);
                    }
                }
            }
        }
        return joinPoint.proceed();
    }
}
